
//let util = require("../../utils/utils");
let app = getApp();
let t = 0;
Page({
    data: {
        stepInfo: {},
        loading: true,
        pointShow: false,
        exchangeSuccess: false,
        loginSuccess: false,
        mapSet: {},
        content: "",
        hoorayShow: false,
        exchange_bl: 0,
        qingzhuImg: app.resPath + "img/qingzhu.jpg"
    },
    onLoad: function(e) {
        // const query = wx.createSelectorQuery();
        // let m = query.select('#myMap')
        // console.log(m.addMakers)
        this.tMap = wx.createMapContext("myMap")
        // console.log(this.tMap)
        // console.log(this.data.mapSet)
        this.loadData();
    },

    loadData() {
        wx.showLoading({
            title: "加载中..."
        })
        Promise.all([this.getTheStep(), this.getMapData(), this.getBl()]).then(resArr=> {
            console.log(resArr)
            resArr[0].total_km = t;
            let km = resArr[0].total_km || 0;
            this.showFinish(km, resArr[1]);
            this.checkComplete(km, resArr[1]);
            var o = resArr[0];
            this.setData({
                exchange_bl: resArr[2],
                stepInfo: o,
                mapSet: resArr[1]
            })
            wx.hideLoading()
            
        }).catch(e=> {
            console.log(e)
            wx.showToast({
              title: '操作失败',
            })
            wx.hideLoading() 
        })
    },

    showPointDetail(e) {
        // console.log(e)
        //等客户提供文案
        return;
        wx.showLoading();
        let n = e.detail.markerId;
        this.getPointData(n).then(res=>{
            this.setData({
                pointShow: true,
                content: res.content
            })
            wx.hideLoading();
        }).catch((e)=> {
            wx.hideLoading();
        })

    },
    showRemainTip() {
        let n = this.data.exchange_bl - this.data.stepInfo.total_cur_effect_step;
        wx.showToast({
          title: '还差' + n + "步可兑换",
        })
    },
    showFinish(km, mapSet) {
        let user = app.getUserInfo();
        let last = null;
        for(let i= 0; i < mapSet.polyline[0].points.length; i++) {
            let o = mapSet.polyline[0].points[i];
            // if(km > o.disAll && (i + 1) < mapSet.polyline[0].points.length && km < mapSet.polyline[0].points[i+1].disAll) {
            //     let user = app.getUserInfo();
                
            //     mapSet.markers[i].width = 40;
            //     mapSet.markers[i].height = 40;                
            //     mapSet.polyline[0].colorList.unshift("#D81E06")
            // }
            // 大于标记点 就标记成自己的头像 然后把上一个标记点变成旗子
            if(km >= (o.disAll / 1000)) {
                mapSet.markers[i].width = 40;
                mapSet.markers[i].height = 40;
                // mapSet.markers[i].iconPath = user.wxUserInfo.avatarUrl;
                
                mapSet.markers[i].iconPath = app.resPath + "img/finish.png";
                if(i > 0) {
                    //mapSet.markers[i-1].iconPath = app.resPath + "img/finish.png";
                    mapSet.polyline[0].colorList.unshift("#E1322F")
                }
            }
            else {
                mapSet.markers[i].iconPath = app.resPath + "img/dot.png";
                if(last === null) {
                    last = i;
                }
            }
        }
            try {
                //获取走到的最后一个点
                let l= mapSet.markers[last-1];
                //如果有这个对象 说明之前创建过这个头像的点 那就直接把它放到数组里面
                if(this.avatarImg) {
                    mapSet.markers.push(this.avatarImg);   
                    console.log(this.avatarImg)
                }
                else { // 没有就创建一个
                    let tx = Object.assign({}, l); // 克隆最后一个走过的 
                    tx.iconPath = user.wxUserInfo.avatarUrl; // 头像改一下
                    tx.zIndex = 99999; // zindex改一下
                    tx.id = 99999; // id改一下
                    tx.callout = {};  // 这个对象变成空
                    tx.linkId = l.id;  // 增加一个目前它和那个点是在一起的标记
                    mapSet.markers.push(tx); 
                    this.avatarImg = tx;
                }
                if(this.avatarImg.linkId != l.id) {
                    this.doMove(this.avatarImg, l.id, mapSet);
                    console.log(mapSet)
                }
            //mapSet.markers[last-1].iconPath = user.wxUserInfo.avatarUrl;
            console.log(mapSet)
          }catch(e){
              console.log(e)
          }
    },
    doMove(tx, id, mapset) {  // 头像对象 新的最新走到的点的id 
        let arr = mapset.markers;
        let index = this.getIndexById(tx.linkId, arr); // 找到之前头像指向的节点的id的索引
        if(index == -1) {  
            return;
        }
        tx.linkId = id; // 让头像的linkid等于最新点的id
        let list = this.getIncreaseStep(index, id, arr); // 从上次的节点开始找 找到新的节点id 获取他们之间的节点 放到数组里面
        if(!list) {
            list = this.getDecreaseStep(index, id, arr);  // 没找到上面的节点 那就往后找 因为有可能步数兑换规则变了 就会变少
        }
        if(!list) {
            return;
        }
        this.move(tx, list);
    },
    move(tx, list) {
        let l = list.shift();
        this.tMap.translateMarker({
            markerId: this.avatarImg.id,
            duration: 1000,
            destination: {longitude: l.longitude, latitude: l.latitude},
            complete: ()=> {
                if(list.length) {
                    this.move(tx, list);
                }
                else {
                    tx.longitude = l.longitude;
                    tx.latitude = l.latitude;
                    console.log(tx, l, this.avatarImg)
                }
            }
        }) 
    },
    //找到增长的节点
    getIncreaseStep(index, id, arr) {
        let list = [];
        for(let i = index; i < arr.length; i++) {
            list.push(arr[i])
            if(arr[i].id == id){
                return list
            }
        }
        return null;
    },
    getDecreaseStep(index, id, arr) {
        let list = [];
        for(let i = index; i >=0; i--) {
            list.push(arr[i])
            if(arr[i].id == id){
                return list
            }
        }
        return null;
    },
    //找到之前的marker所在的index
    getIndexById(id, arr) {
        for(let i = 0; i < arr.length; i++) {
            if(arr[i].id == id) {
                return i
            }
        }
        return -1;
    },
    checkComplete(km, mapSet) {
        let list = mapSet.polyline[0].points;
        let n = list[list.length - 1].disAll / 1000;
        if(km > n) {
            let b = wx.getStorageSync('cz_complete');
            if(b != 1) {
                this.setData({
                    hoorayShow: true
                })
                wx.setStorage({
                    data: 1,
                    key: 'cz_complete',
                })
            }
        }
        else {
            wx.setStorage({
              data: 0,
              key: 'cz_complete',
            })
        }
    },
    //比例
    getBl(e) {
        // return new Promise((rs,rj)=>{
        //     // wx.request({
        //     //     url: app.resPath + "json/config.json",
        //     //     method: "GET",
        //     //     success (res) {
        //     //      // console.log(res)
        //     //      rs(res.data.baseInfo.exchange_bl);
        //     //     },
        //     //     fail (e) {
        //     //         rj(e)
        //     //     }
        //     // })            
            
        // }); 
        return app.getConfig().then(res=>{
            // console.log(res)
            return res.baseInfo.exchange_bl
        })

    },

    getPointData(n) {
        return new Promise((rs,rj)=>{
            wx.request({
                url: app.resPath + "json/point/" + n +".json",
                method: "GET",
                success (res) {
                 // console.log(res)
                 rs(res.data);
                },
                fail (e) {
                    rj(e)
                }
            })            
            
        });        
    },
    pointHide() {
        this.setData({
            pointShow: false,
            content: ""
        })
    },
    //获取步数等信息
    getTheStep() {
        return new Promise((rs, rj)=> {
            wx.request({
                url: app.domain + "ssm/appWebServ/feet/getStepInfo",
                data: {
                    openid: app.openid
                },
                success (res) {
                  console.log(res)
                  rs(res.data.stepInfo);
                },
                fail (e) {
                    rj(e)
                }
            }) 
        })
               
    },
    //获取路线信息
    getMapData() {
        return new Promise((rs,rj)=>{
            wx.request({
                url: app.resPath + "json/road.json",
                method: "GET",
                success (res) {
                 // console.log(res)
                 rs(res.data.data);
                },
                fail (e) {
                    rj(e)
                }
            })            
            
        });

    },
    hoorayHide() {
        this.setData({
            hoorayShow: false
        })
    },
    doExchange() {
        t = 600;
        this.loadData();
        return;
        wx.showLoading({
          title: '处理中...',
        })
        wx.request({
            url: app.domain + "/ssm/appWebServ/feet/exchangeStep",
            data: {
                openid: app.openid
            },
            success: (res)=> {
                wx.showToast({
                    title: '已兑换',
                })
                this.loadData();
            },
            fail (e) {
               wx.showToast({
                 title: '操作失败',
               })
            },
            complete() {
                wx.hideLoading();
            }
        }) 
    },
    gotoRank() {
        wx.navigateTo({
            url: "/pages/paiming/paiming"
        });
    }
    // previewImage: function() {
    //     wx.previewImage({
    //         urls: [ this.data.roadMapSrc ]
    //     });
    // }

});
